﻿using Deployment.Data.Deploy.Steps.Tasks;
using Deployment.Data.SQL.Tasks.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;


namespace Deployment.Data.SQL.Tasks
{
    public class SQLScriptTask : AbstractSQLTask
    {
        private const string SCRIPT_ELEMENT = "Script";

        private string _ScriptFile;

        public string Script
        {
            get { return _ScriptFile; }
            set
            {
                if (_ScriptFile != value)
                {
                    _ScriptFile = value;
                    OnPropertyChanged("Script");
                }
            }
        }

        

        protected override void readSubElement(XmlReader reader)
        {
            if (reader.Name.Equals(SCRIPT_ELEMENT, StringComparison.CurrentCultureIgnoreCase))
                Script = reader.ReadElementContentAsString();
        }

        protected override void writeSubElements(XmlWriter writer)
        {
            writer.WriteElementString(SCRIPT_ELEMENT, "", Script);
        }

        protected override bool performSQLTaskValidation(Environment.Environment executionEvnironment, out string message)
        {
            if (string.IsNullOrEmpty(Script))
            {
                message = string.Format("Task [{0}].[{1}], Script value is null or blank.", this.Id, this.Description);
                return false;
            }

            if (!File.Exists(Script))
            {
                message = string.Format("Could not locate Script File [{0}]", Script);
                return false;
            }
            message = null;
            return true;
        }

        protected override void AbstractSQLTaskClone(AbstractSQLTask copy)
        {
            SQLScriptTask task = copy as SQLScriptTask;
            if (task == null)
                throw new InvalidCastException("copy must be an instance of SQLScriptTask");
            task.Script = this.Script;
            copy = task;
        }

        protected override string getTaskTypeDescription()
        {
            return "SQL Script Task";
        }

        protected override AbstractTaskControl createUserControl()
        {
            return new SQLScriptTaskControl();
        }

        protected override bool check_ContentIsSavable()
        {
            return (!string.IsNullOrEmpty(this.Connection) && !string.IsNullOrEmpty(this.Script) && File.Exists(this.Script));
        }
    }
}
